const {Document} = require('camo')
const Character = require('./character')

const tinycolor = require('tinycolor2')
const chalk = require('chalk')

// Just an organised party (read: team, group) of Characters.
class Party extends Document {
  constructor() {
    super()

    this.schema({
      members: [Character],
      //name: {type: String, default: 'Unnamed Party'},
      colorHue: {type: Number, min: 0, max: 1},
      //discordRoleID: {type: String, required: false}, // Will be automatically generated
    })
  }

  get colorHex() {
    return tinycolor.fromRatio({h: this.colorHue, s: 0.6, v: 1.0}).toHexString()
  }

  async addCharacter(character) {
    if (character.partyID) {
      // Remove the character from their old party
      const origParty = await character.getParty()
      await origParty.rmCharacter(character)
    }

    character.partyID = this._id
    this.members.push(character)

    await Promise.all([this.save(), character.save()])
  }

  async rmCharacter(character) {
    character.partyID = null
    await character.save()

    this.members = this.members.filter(mem => mem._id !== character._id)

    if (this.members.length === 0) {
      // We don't need to exist anymore.
      // #relatable
      await this.delete()
    } else {
      await this.save()
    }
  }

  /*
  async getRole(guild) {
    // Create the role, if it doesn't exist already.
    if (!this.discordRoleID) {
      const role = await guild.createRole()
      await this.updateRole(role)

      this.discordRoleID = role.id
    }

    return guild.roles.get(this.discordRoleID)
  }

  async updateRole(role) {
    // Update party role details.
    await role.edit({
      name: this.name,
      color: this.colorHex,
    })
  }

  async assignRoles(guild) {
    const partyRole = await this.getRole(guild)
    await this.updateRole(partyRole)

    for (const character of this.members) {
      if (!character.discordID) {
        continue
      }

      const member = guild.members.get(character.discordID)
      member.addRole(partyRole)
    }
  */

  static async of(characters) {
    const party = this.create({
      characters: [],
      colorHue: Math.random(),
    })

    for (const character of characters) {
      await party.addCharacter(character)
    }

    return party
  }
}

module.exports = Party
